﻿using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace Best.SmartCms.API.WebAPIExtensions
{
    /// <summary>
    /// 
    /// </summary>
    public class StatusCodeCheckMiddleware
    {
        private readonly RequestDelegate _next;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        public StatusCodeCheckMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static bool IsHttpError(HttpResponse response)
        {
            return response.StatusCode >= 400;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            if (context == null) throw new ArgumentNullException(nameof(context));

            await _next.Invoke(context).ConfigureAwait(false);

            var response = context.Response;
            if (IsHttpError(response) && string.IsNullOrEmpty(response.ContentType))
            {
                var result = new StatusHttpResult
                {
                    ErrorCode = response.StatusCode,
                    ErrorMessage = ((HttpStatusCode) response.StatusCode).ToString()

                };
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonConvert.SerializeObject(result)).ConfigureAwait(false);
            }
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class StatusHttpResult
    {
        /// <summary>
        /// 
        /// </summary>
        public int ErrorCode { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string ErrorMessage { get; set; }
    }

    /// <summary>
    /// 
    /// </summary>
    public static class StatusCodeCheckMiddlewareExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseStatusCodeCheckMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<StatusCodeCheckMiddleware>();
        }
    }
}
